// import request from '@/utils/http'
// import { BaseResult } from '@/types/axios'
import { BaseResult } from '@/types/axios'
import { UserInfo } from '@/types/store'
import avatar from '@imgs/user/avatar.png'
import axios from 'axios'
import { ElMessage } from 'element-plus'

// 从环境变量获取API基础路径
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:8080';
const API_PREFIX = import.meta.env.VITE_BASE_URL || '/api';

// 构建完整的API路径
const getApiUrl = (endpoint: string) => `${API_BASE_URL}${API_PREFIX}${endpoint}`;

// 创建axios实例
const axiosInstance = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
});

// 设置请求拦截器，添加认证令牌
axiosInstance.interceptors.request.use(
  (config) => {
    // 排除登录和退出登录等不需要token的路径
    const noTokenRequired = ['/user/login', '/user/logout'];
    const currentPath = config.url || '';
    
    // 如果不是登录或退出登录请求，则添加token
    if (!noTokenRequired.some(path => currentPath.includes(path))) {
      const token = localStorage.getItem('token');
      if (token) {
        config.headers['Authorization'] = `Bearer ${token}`;
      }
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 用户接口响应数据类型
interface LoginResponse {
  code: number;
  msg: string;
  message: string;
  data: {
    token: string;
    userInfo: {
      id: number;
      nickname: string;
      real_name: string;
      password: string;
      email: string;
      name: string;
      avatar: string;
      group: Array<{
        id: number;
        alias: string;
        label: string;
        remark: string;
        sort: number;
        status: number;
        menus: any[] | null;
      }>;
    };
  };
}

export class UserService {
  // 登录接口，向后端发送POST请求
  static async login(options: { body: string }): Promise<BaseResult> {
    try {
      // 解析登录信息
      const loginData = JSON.parse(options.body);
      
      // 构建登录API的完整URL
      const loginUrl = getApiUrl('/user/login');
      
      // 使用axios发送POST请求到后端
      const response = await axiosInstance.post(loginUrl, {
        username: loginData.username,
        password: loginData.password
      });
      
      // 获取响应数据
      const responseData: LoginResponse = response.data;
      
      // 检查登录是否成功
      if (responseData.code === 200 && responseData.data) {
        // 存储token到localStorage和sessionStorage
        const token = responseData.data.token;
        localStorage.setItem('token', token);
        sessionStorage.setItem('accessToken', token);
        
        console.log('登录成功，已存储token:', token); // 调试信息
        
        // 存储用户信息到localStorage
        localStorage.setItem('userInfo', JSON.stringify(responseData.data.userInfo));
        
        // 返回成功响应
        return {
          code: 200,
          message: responseData.message || '登录成功',
          data: {
            accessToken: token
          }
        };
      } else {
        // 返回错误响应
        return {
          code: responseData.code || 401,
          message: responseData.msg || '登录失败',
          data: null
        };
      }
    } catch (error) {
      console.error('登录请求出错:', error);
      
      // 获取axios错误信息
      let errorMessage = '登录请求失败';
      if (axios.isAxiosError(error)) {
        errorMessage = error.response?.data?.message || error.message;
      } else if (error instanceof Error) {
        errorMessage = error.message;
      }
      
      // 返回错误响应
      return {
        code: 500,
        message: errorMessage,
        data: null
      };
    }
  }

  // 退出登录，清空localStorage
  static async logout(): Promise<BaseResult> {
    try {
      // 构建退出登录API的完整URL
      const logoutUrl = getApiUrl('/user/logout');
      
      // 尝试向后端发送退出登录请求
      // 无论请求成功与否，都会清空localStorage
      try {
        await axiosInstance.post(logoutUrl);
      } catch (e) {
        console.warn('退出登录请求失败，但会继续清空本地数据:', e);
      }
      
      // 清空localStorage中的所有内容
      localStorage.clear();
      
      // 提示用户已退出登录
      ElMessage.success({
        message: '已成功退出登录',
        type: 'success',
        duration: 2000
      });
      
      // 返回成功响应
      return {
        code: 200,
        message: '退出登录成功',
        data: null
      };
    } catch (error) {
      console.error('退出登录处理出错:', error);
      
      // 尽管发生错误，仍然清空localStorage
      localStorage.clear();
      
      // 返回错误响应
      return {
        code: 500,
        message: '退出登录处理出错，但已清空本地登录信息',
        data: null
      };
    }
  }

  // 获取用户信息 - 从localStorage获取存储的用户信息
  static getUserInfo(): Promise<BaseResult<UserInfo>> {
    return new Promise((resolve) => {
      try {
        // 从localStorage获取用户信息
        const userInfoString = localStorage.getItem('userInfo');
        
        if (userInfoString) {
          const storedUserInfo = JSON.parse(userInfoString);
          
          // 返回用户信息
          resolve({
            code: 200,
            message: '获取用户信息成功',
            data: {
              id: storedUserInfo.id,
              name: storedUserInfo.real_name || storedUserInfo.name,
              username: storedUserInfo.name,
              avatar: storedUserInfo.avatar || avatar,
              email: storedUserInfo.email || 'art.design@gmail.com'
            }
          });
        } else {
          // 若localStorage中无用户信息，返回默认值
          resolve({
            code: 200,
            message: '获取用户信息成功',
            data: {
              id: 1,
              name: '未知用户',
              username: 'Unknown User',
              avatar: avatar,
              email: 'art.design@gmail.com'
            }
          });
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        
        // 返回默认用户信息
        resolve({
          code: 200,
          message: '获取用户信息成功',
          data: {
            id: 1,
            name: '默认用户',
            username: 'Default User',
            avatar: avatar,
            email: 'art.design@gmail.com'
          }
        });
      }
    });
  }
}
